#include <iostream>

#include <QVector3D>
#include <QTextStream>

#include <libz800.h>

#include "DlgProperties.h"

DlgProperties::DlgProperties(QWidget *parent)
: QDialog(parent)
, _dev(NULL)
{
	setupUi(this);
}

void DlgProperties::setDevice(z800_device *dev)
{
	_dev = dev;
}

void DlgProperties::updateRow(int r)
{
	QString name = tableWidget->item(r, 0)->text();

	struct z800_property prop;
	if(z800_get_property_meta_info(_dev, name.toAscii().data(), &prop) == 0)
	{
		qWarning("z800_get_property_meta_info failed()");
		return;
	}

	if(prop.default_value > -1)
	{
		tableWidget->setItem(r, 3, new QTableWidgetItem(QString::number(prop.min_value)));
		tableWidget->setItem(r, 4, new QTableWidgetItem(QString::number(prop.max_value)));
	}
	else
	{
		tableWidget->setItem(r, 3, new QTableWidgetItem("-"));
		tableWidget->setItem(r, 4, new QTableWidgetItem("-"));
	}

	if(prop.default_value == -1)
	{
		tableWidget->setItem(r, 5, new QTableWidgetItem("-"));
	}
	else
	{
		tableWidget->setItem(r, 5, new QTableWidgetItem(QString::number(prop.default_value)));
	}

	int v;
	if(z800_read_property(_dev, name.toAscii().data(), &v, Z800_FALSE) == 0)
	{
		qWarning("z800_read_property() failed");
		tableWidget->setItem(r, 1, new QTableWidgetItem("?"));
	}
	else
	{
		tableWidget->setItem(r, 1, new QTableWidgetItem(QString::number(v)));
	}

	if(prop.stereo)
	{
		if(z800_read_property(_dev, name.toAscii().data(), &v, Z800_TRUE) == 0)
		{
			qWarning("z800_read_property() failed");
			tableWidget->setItem(r, 2, new QTableWidgetItem("?"));
		}
		else
		{
			tableWidget->setItem(r, 2, new QTableWidgetItem(QString::number(v)));
		}
	}
	else
	{
		tableWidget->setItem(r, 2, new QTableWidgetItem("-"));
	}
}

void DlgProperties::on_refreshPushButton_pressed()
{
	QList<QTableWidgetItem *> selected = tableWidget->selectedItems();
	if(selected.empty())
	{
		return;
	}

	updateRow(selected.first()->row());
}

void DlgProperties::update()
{
	const char * const *propertyNames = z800_get_properties(_dev);

	if(propertyNames == NULL)
	{
		qWarning("z800_get_properties failed()");
		return;
	}

	while(tableWidget->rowCount())
		tableWidget->removeRow(0);

	for(; *propertyNames; ++propertyNames)
	{
		QApplication::processEvents();

		int r = tableWidget->rowCount();
		tableWidget->insertRow(r);
		tableWidget->setItem(r, 0, new QTableWidgetItem(*propertyNames));

		updateRow(r);
	}
}

void DlgProperties::on_tableWidget_itemSelectionChanged()
{
	QString property = selectedProperty();

	refreshPushButton->setEnabled(property != "");

	// editPushButton->setEnabled(property != "" && property != "version");
}

QString DlgProperties::selectedProperty()
{
	QList<QTableWidgetItem *> selected = tableWidget->selectedItems();
	if(selected.empty())
	{
		return "";
	}

	return tableWidget->item(selected.first()->row(), 0)->text();
}
